<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>

			<template #content>
				<view class="content" style="height: 100%;width: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container TitleImageRelative">
							<view class="titleImage">
								<image src="../css/img/shenhe.png" v-show="readOnlyShow">
								</image>
							</view>
							<!-- 											<u-icon slot="right" name="arrow-right"></u-icon> -->
							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验编号:">
											<u--input v-model="baseFormData.BillNO" placeholder="自动带出检验编号" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="产品名称:">
											<u--input v-model="baseFormData.ProductName" placeholder="自动带出产品名称" readonly
												border="none" /></u--input>
										</u-form-item>
									</u-col>

									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验日期:">
											<u--input v-model="baseFormData.BillDate" placeholder="自动带出检验日期" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验数量:" required>
											<u--input v-model="baseFormData.CkAmount" placeholder="自动带出检验数量" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="合格数量:" required>
											<!--:readonly='readOnlyShow' @input="addAmount('合格')" type="number" -->
											<u--input v-model="baseFormData.OkAmount" placeholder="自动带出合格数量" readonly
												type="number" border="none" /></u--input>
										</u-form-item>
									</u-col>

									<u-col span="4">
										<u-form-item labelWidth="auto" label="不合格数量:">
											<u--input v-model="baseFormData.BadAmount" placeholder="自动带出不合格数量" readonly
												type="number" border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="良率:" required>
											<u--input v-model="baseFormData.BadRate+'%'" placeholder="自动带出良率" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验结果:" required @click="changeResultshow">
											<u--input v-model="baseFormData.ResultName" placeholder="请选择检验结果" readonly
												border="none" /></u--input>
										</u-form-item>
									</u-col>

									<u-col span="4">
										<u-form-item labelWidth="auto" label="审核状态:">
											<u--input v-model="baseFormData.ApproveName" placeholder="自动带出审核状态" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>


								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审核人:">
											<u--input v-model="baseFormData.Approver" placeholder="自动带出审核人" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审核时间:">
											<u--input v-model="baseFormData.ApproveTime" placeholder="自动带出审核时间" readonly
												border="none" /></u--input>
										</u-form-item>
									</u-col>

									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验员:">
											<u--input v-model="baseFormData.QCEmplName" placeholder="自动带出检验员" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>

								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="派工单编号:">
											<u--input v-model="baseFormData.PGBillNo" placeholder="自动带出派工单编号" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="工序:">
											<u--input v-model="baseFormData.ProcedureName" placeholder="自动带出工序" readonly
												border="none" /></u--input>
										</u-form-item>
									</u-col>

									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验类型:">
											<u--input v-model="baseFormData.FTypeName" placeholder="检验类型" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
							</u--form>

						</view>
						<view class="table" v-show="CkAmountList.length>0">
							<table>
								<tr>
									<th>序号</th>
									<th>检验项目</th>
									<th>检验标准</th>
									<th>上极限</th>
									<th>下极限</th>
									<th>检验值</th>
									<th><text style="color: red;">*</text>检验结果</th>
								</tr>
								<tr v-for="(item, index) in CkAmountList">
									<td>{{index + 1}}</td>
									<td>
										<u--textarea v-model="item.FQCItemName" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.JYBZ" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.PoorWork" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.PoorNormally" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.JYJG" autoHeight border="none"
											@blur="JYJGInput(item,index)" :disabled='readOnlyShow'
											class="fixed-textarea"></u--textarea>
									</td>
									<td @click="AddZFResult(index)">
										<u--textarea v-model="item.ZFResultName" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
								</tr>
							</table>
						</view>

						<view class="table" v-show="tableData.length>0">
							<table>
								<tr>
									<th>序号</th>
									<th>检验项目</th>
									<th> <text style="color: red;">*</text>不合格数量</th>
								</tr>
								<tr v-for="(item, index) in tableData">
									<td>{{index + 1}}</td>
									<td>
										<u--textarea v-model="item.ReasonName" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td> <u-number-box v-model="item.BadNum" :min="0" :disabled="ApproveButton=='已审核'"
											@input='AddBadNumChild'></u-number-box>
									</td>
								</tr>
							</table>
						</view>
					</view>
					<view class="bottomBtns2">
						<button class="button0" @click='exitButton'>返回报工页面</button>
						<button class="button1" block @click="submit('保存')"
							v-show="ApproveButton=='保存'||ApproveButton=='未审核'">
							保存
						</button>
						<button v-show="ApproveButton=='未审核'" class="button2" block @click="toexamine"
							v-if='ApproveBack("审核")'>
							审核
						</button>
					</view>
				</view>

			</template>
		</st-mc-framework>
		<u-action-sheet :actions="ZFResultList" :show="ZFResultShow" @select="ZFResultClick"
			@close="ZFResultShow=false"></u-action-sheet>
		<u-action-sheet :actions="Resultlist" :show="Resultshow" @select="ResultClick"
			@close="Resultshow=false"></u-action-sheet>
		<u-action-sheet :actions="ApproveList" :show="ApproveShow" @select="ApproveSClick"
			@close="ApproveShow=false"></u-action-sheet>
		<u-toast ref="uToast"></u-toast>


		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm'
			:showCancelButton="modaltitle=='审核'||modaltitle=='提示'||modaltitle=='通知'" :confirmText='confirmText'
			:cancelText="cancelText" @cancel='modalcancel'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {
				baseFormData: {
					InspectionID: 0,
					BillNO: "",
					FType: "",
					ProductID: '',
					ProductName: "",
					BillDate: "",
					CkAmount: null,
					OkAmount: null,
					BadAmount: null,
					BadRate: null,
					Result: null,
					ResultName: '',
					Approve: null,
					ApproveName: '',
					Approver: null,
					ApproveTime: null,
					PGBillNo: "",
					QCEmplID: '',
					QCEmplName: "",
					FTypeName: '',
					ProcedureName: '',
					EquipmentID: null
				},
				value: '',
				CkAmountList: [],
				tableData: [],
				obj: {},
				Resultshow: false,
				Resulttitle: '',
				Resultlist: [],
				ApproveShow: false,
				ApproveList: [{
						name: '未审核',
						id: 1
					},
					{
						name: '已审核',
						id: 0
					}
				],
				ProcedureList: [],
				HostApproveButton: '',
				ApproveButton: '',
				BtnApprove: [],
				// ApproveBackShow: false,
				cancelText: '取消',
				confirmText: '确认',
				initData: {},
				initObj: {},
				readOnlyShow: false, //按钮禁用
				ModuleTitle: '', //标题名称
				showMLoading: false, //是否加载
				loadingName: '正在加载中……', //加载名称
				modalshow: false, //提示显示
				modaltitle: '', //提示名称
				modalcontent: '', //提示内容
				FWorkshopID: null,
				ZFResultIndex: null,
				ZFResultShow: false,
				// 判断结果
				ZFResultList: [{
					name: '合格',
					id: 1
				}, {
					name: '不合格',
					id: -1
				}],

			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName

		},
		onLoad(onlod) {
			var that = this
			console.log(onlod);
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			let foundNode = null;
			console.log(appConfigInfo.ModuleInfo_All);
			for (const module of appConfigInfo.ModuleInfo_All) {
				if (module.TreeTypeName === '生产检验') {
					for (const node of module.Node) {
						if (node.APFunName === '自检') {
							foundNode = JSON.parse(JSON.stringify(node));
							break; // 找到后立即退出内层循环  
						}
					}
					if (foundNode) {
						break;
					}
				}
			}
			this.BtnApprove = foundNode['IconApprove'];
			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			this.ApproveButton = onlod.ApproveButton
			this.HostApproveButton = onlod.ApproveButton
			var iteminfo
			if (onlod.obj) {
				this.obj = JSON.parse(onlod.obj)
				iteminfo = {
					FTypeName: this.obj.FTypeName,
					ProcedureName: this.obj.ProcedureName,
					JobOrderID: this.obj.JobOrderID,
					ProcedureID: this.obj.ProcedureID,
					InspectionID: this.obj.InspectionID,
				}
				this.assignFormData(this.baseFormData, iteminfo);
			}
			if (that.baseFormData.InspectionID) {
				setLoading(true);
				this.queryList(that.baseFormData.InspectionID);
				return;
			}
			this.list()
			setLoading(false);
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		methods: {
			ZFResultClick(e) {
				var that = this
				var formDefaults = {
					ZFResult: e.id,
					ZFResultName: e.name
				}
				console.log(formDefaults);
				that.assignFormData(that.CkAmountList[that.ZFResultIndex], formDefaults);
				that.ZFResultShow = false
			},
			AddZFResult(index) {
				var that = this
				that.ZFResultIndex = index
				that.ZFResultShow = true
			},
			JYJGInput(ite, iteIndex) {
				var that = this
				var formDefaults = {}
				if (ite.PoorWork && ite.PoorNormally) {
					if (Number(ite.JYJG)) {
						if (Number(ite.PoorWork) > Number(ite.JYJG) || Number(ite.PoorNormally) < Number(ite
								.JYJG)) {
							formDefaults = {
								ZFResult: that.ZFResultList[1].id,
								ZFResultName: that.ZFResultList[1].name,
							}
						} else {
							formDefaults = {
								ZFResult: that.ZFResultList[0].id,
								ZFResultName: that.ZFResultList[0].name,
							}
						}
					}

				}
				that.assignFormData(that.CkAmountList[iteIndex], formDefaults);
				that.$forceUpdate()
			},
			modalcancel() {
				var that = this
				that.modalshow = false
				if (that.modaltitle == '当前页面未保存，是否先保存在关闭？') {
					that.AndSetStateData()
				}
			},

			modalconfirm() {
				var that = this
				that.modalshow = false
				if (that.modaltitle == '审核') {
					that.submit('审核')
				} else if (that.modaltitle == '通知') {

					var obj = {
						FQty: that.baseFormData.ApproveName == '已审核' ? that.baseFormData.BadAmount : '返回',
						FSumQty: that.obj.FDailyQtt ? that.obj.FDailyQtt : 0,
						FDailyQtt: that.obj.FDailyQtt ? that.obj.FDailyQtt : 0,
						InspectionID: that.baseFormData.InspectionID ? that.baseFormData.InspectionID : 0
					}

					this.GoToLevel()
					uni.$emit('refselfValue', obj);
				}
			},
			GoToLevel() {
				var initData = JSON.parse(JSON.stringify(this.$store.state.GuyueModule.ModuleData_select));
				var parentData = initData[initData.length - 1]
				this.$refs.framework.ToLevel(parentData)
			},

			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					Vue.set(target, key, defaults[key]);
				});
				this.$forceUpdate();
			},
			UpdateAssignFormData(formDefaults) {
				this.assignFormData(this.baseFormData, formDefaults)
			},
			replaceFormData(target, source, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					target[key] = source[key] || defaults[key];
				});
				this.$forceUpdate()
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			showModal(title, content, confirmText, cancelText) {
				this.confirmText = confirmText
				this.cancelText = cancelText
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},

			ApproveBack(str) {
				let that = this;
				let Type = false;
				if (that.BtnApprove.length) {
					Type = that.BtnApprove.some(item => {
						return item.MenuName == str
					})
				}
				that.ApproveBackShow = Type
				return Type;
			},
			toexamine() {
				var that = this
				that.showModal('审核', '确定审核吗？', '确认', '取消');


			},

			AddBadNumChild() {
				var num = 0
				this.tableData.forEach(item => {
					num = num + item.BadNum
				})
				const formDefaults = {
					BadAmount: num
				};
				this.assignFormData(this.baseFormData, formDefaults)
				this.addAmount('不合格')
			},

			submit(str) {
				var that = this
				var show = true
				var msg
				var tableDataAll = JSON.parse(JSON.stringify(that.tableData))
				var CkAmountListAll = JSON.parse(JSON.stringify(that.CkAmountList))
				const {
					ResultName,
					CkAmount,
					BadAmount,
					OkAmount,
				} = that.baseFormData;

				if (CkAmount == '' || CkAmount == null) {
					msg = '请输入检验数量'
					show = false
				} else if (ResultName == '' || ResultName == null) {
					msg = '请输入检验结果'
					show = false
				} else if (Number(BadAmount) == 0) {
					show = true
				} else if (Number(OkAmount) == 0) {
					show = true
				} else if (BadAmount == '' || BadAmount == null) {
					msg = '请输入不合格数量'
					show = false
				} else if (OkAmount == '' || OkAmount == null) {
					msg = '请输入合格数量'
					show = false
				}
				CkAmountListAll.some((item, index) => {
					if (item.PoorNormally || item.PoorWork) {
						if (!item.JYJG) {
							msg = `请输入第${index + 1}行检验值`;
							show = false;
							return true;
						}
					}
					if (item.ZFResult == '' || item.ZFResult == null) {
						msg = '请选择检验结果';
						show = false;
					}
					return false; // 继续遍历下一个
				});

				if (show) {
					that.SubmitBtn(str, tableDataAll, CkAmountListAll)
				} else {
					that.showModal('报错', msg);
				}
			},
			SubmitBtn(str, tableDataAll, CkAmountListAll) {
				var that = this
				var cmd
				const {
					ResultName,
					CkAmount,
					BadAmount,
					OkAmount,
					ProductName,
					ProductID,
					QCEmplID,
					JobPROCID,
					Result,
					ProcedureID,
					JobOrderID,
					QCEmplName
				} = that.baseFormData;
				tableDataAll.forEach(item => {
					if (item.PoorWork == '' || item.PoorWork == null) {
						item.PoorWork = '@'
					}
					if (item.PoorNormally == '' || item.PoorNormally == null) {
						item.PoorNormally = '@'
					}
					if (item.JYJG == '' || item.JYJG == null) {
						item.JYJG = '@'
					}
				})
				CkAmountListAll.forEach(item => {
					if (item.JYJG == '' || item.JYJG == null) {
						item.JYJG = '@'
					}
					if (item.JYBZ == '' || item.JYBZ == null) {
						item.JYBZ = '@'
					}
					if (item.PoorWork == '' || item.PoorWork == null) {
						item.PoorWork = '@'
					}
					if (item.PoorNormally == '' || item.PoorNormally == null) {
						item.PoorNormally = '@'
					}
				})
				that.baseFormData.InspectionID = that.baseFormData.InspectionID ? that.baseFormData.InspectionID : 0
				var obj = {
					CkAmount: CkAmount,
					InspectionID: that.baseFormData.InspectionID,
					ProductName: ProductName,
					ProductID: ProductID,
					QCEmplID: QCEmplID,
					JobPROCID: JobPROCID,
					FType: 'ZJ',
					FResult: Result,
					ProcedureID: ProcedureID,
					BadAmount: BadAmount,
					JobOrderID: JobOrderID,
					JYJG: CkAmountListAll.map(item => item.JYJG).join(','),
					CheckupProductCodeDeID: CkAmountListAll.map(item => item.CheckupProductCodeDeID)
						.join(','),
					ZFResult: CkAmountListAll.map(item => item.ZFResult).join(','),
					JYBZ: CkAmountListAll.map(item => item.JYBZ).join(','),
					PoorWork: CkAmountListAll.map(item => item.PoorWork).join(','),
					PoorNormally: CkAmountListAll.map(item => item.PoorNormally).join(','),
					UpID: CkAmountListAll.map(item => item.UpID).join(','),
					FQCItemID: CkAmountListAll.map(item => item.FQCItemID).join(','),
					CheckupProductID: tableDataAll[0].CheckupProductID,
					BadReasonID: tableDataAll.map(item => item.BadReasonID).join(','),
					BadNum: tableDataAll.map(item => item.BadNum).join(','),
					CheckupProductCodeDefectDeID: tableDataAll.map(item => item
							.CheckupProductCodeDefectDeID)
						.join(','),

				}
				if (that.baseFormData.InspectionID == 0) {
					cmd = 'insertJYRecord'
				} else {
					cmd = 'saveJYRecord'
					obj.InspectionDefectDeID = tableDataAll.map(item => item.InspectionDefectDeID).join(',')
					obj.InspectionDeID = CkAmountListAll.map(item => item.InspectionDeID).join(',')
				}
				console.log(obj);
				that.Submitmodifications(str, cmd, obj)
			},
			Submitmodifications(str, cmd, obj) {
				var that = this
				try {
					that.Request.request(cmd, obj, (ret) => {
						console.log(ret);
						if (ret.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})

							that.ApproveButton = '未审核'
							var NewInspectionID
							if (ret.data.ds && ret.data.ds.length > 0) {
								NewInspectionID = ret.data.ds[0].InspectionID
							} else {
								NewInspectionID = that.baseFormData.InspectionID
							}
							const formDefaults = {
								InspectionID: NewInspectionID
							};
							that.assignFormData(that.baseFormData, formDefaults)
							switch (str) {
								case '审核':
									that.Request.request('ApproveJY', {
										InspectionID: NewInspectionID
									}, (res) => {
										console.log(res);
										if (res.status == 200) {
											that.ApproveButton = '已审核'
											that.$refs.uToast.show({
												title: '审核',
												type: 'success',
												message: '审核成功'
											})
											that.refreshqueryList({
												FSumQty: that.obj.FDailyQtt,
												FDailyQtt: that.obj.FDailyQtt,
												FQty: that.baseFormData.BadAmount,
												InspectionID: that.baseFormData.InspectionID
											})
										}
									})
									break;
								case '退出':
									that.AndSetStateData()
									break;
								default:
									console.log('触发');
									// if (that.ApproveBackShow) {
									console.log('触发');
									that.queryList(that.baseFormData.InspectionID)
									// } else {
									// 	console.log('触发');
									// 	that.refreshqueryList({
									// 		FSumQty: that.obj.FDailyQtt,
									// 		FDailyQtt: that.obj.FDailyQtt,
									// 		FQty: 0,
									// 		InspectionID: that.baseFormData.InspectionID
									// 	})
									// }
							}


						} else {
							that.showModal('报错', ret.data.ds[0].msg, '确认', '取消');
						}
					})

				} catch (e) {
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},

			refreshqueryList(res) {
				setTimeout(() => {
					this.GoToLevel()
					uni.$emit('refselfValue', res);
				}, 1000)
			},
			getTarget(arrayName, status) {
				// 1. 根据arrayName获取对应数组
				const targetArray = this[arrayName];
				// 2. 在目标数组中查找
				const obj = targetArray.find(item => item.id === status);
				return obj.name || '';
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getInspectionDetail', {
						InspectionID: id
					}, (ret) => {
						console.log(ret);
						that.showMLoading = false
						if (ret.status == 200) {
							var [firstItem] = ret.data.ds;
							firstItem.ApproveTime = formatDateTime(firstItem.ApproveTime)
							that.assignFormData(that.baseFormData, firstItem)
							const {
								ApproveName,
							} = that.baseFormData;
							that.readOnlyShow = ApproveName === '已审核' ? true : false;
							that.ApproveButton = ApproveName === '已审核' ? '已审核' : '未审核';
							ret.data.ds1.map((item) => {
								item.ZFResultName = that.getTarget('ZFResultList', item.ZFResult)
							})
							ret.data.ds2.forEach(item => {
								if (item.BadNum == null) {
									item.BadNum = 0;
								}
							});
							that.CkAmountList = ret.data.ds1
							that.tableData = ret.data.ds2
							that.$forceUpdate()
						}
					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					that.showMLoading = false
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
					this.$forceUpdate()
				}
			},


			resettableData() {
				var that = this
				that.$nextTick(() => {
					that.tableData.forEach(item => {
						item.BadNum = 0
					})
				})




			},
			addAmount(str) {
				const that = this;
				const formDefaults = {};
				const {
					CkAmount,
					OkAmount: qualifiedAmount,
					BadAmount: defectiveAmount
				} = that.baseFormData;

				// 统一校验函数
				const validateNumber = (value, min = 0, max = CkAmount) => {
					const num = Number(value);
					if (num < min) return `不能小于${min}`;
					if (num > max) return `不能大于检验数量`;
					return null;
				};

				// 核心计算逻辑
				const calculateFields = () => {
					formDefaults.CkAmount = Number(qualifiedAmount) + Number(defectiveAmount);
					// 避免除以零
					formDefaults.BadRate = Number(formDefaults.CkAmount) > 0 ?
						((Number(formDefaults.OkAmount || qualifiedAmount) / Number(formDefaults.CkAmount)) * 100)
						.toFixed(2) : 0;
				};

				// 主逻辑处理
				switch (str) {
					// case '合格':
					// 	if (CkAmount == null || CkAmount <= 0) {
					// 		that.showModal('报错', '检验数量必须大于0', '确认', '取消');
					// 		break;
					// 	}

					// 	const okError = validateNumber(qualifiedAmount);
					// 	if (okError) {
					// 		that.showModal('报错', `合格数量${okError}`, '确认', '取消');
					// 		formDefaults.OkAmount = 0;
					// 		formDefaults.BadAmount = 0;
					// 		that.resettableData()
					// 	} else {
					// 		calculateFields();
					// 	}
					// 	break;

					case '不合格':
						if (CkAmount == null || CkAmount <= 0) {
							that.showModal('报错', '请先输入检验数量', '确认', '取消');
							break;
						}

						const defectiveError = validateNumber(defectiveAmount);
						if (defectiveError) {
							that.showModal('报错', `不合格数量${defectiveError}`, '确认', '取消');
							formDefaults.BadAmount = 0;
							formDefaults.OkAmount = CkAmount;
							formDefaults.BadRate = 100;
							that.resettableData()
						} else {
							calculateFields();
						}
						break;

					default:
						console.warn('未知操作类型:', str);
						return;
				}

				// 统一更新数据
				that.UpdateAssignFormData(formDefaults);
			},
			// 	addAmount(str) {
			// 		var that = this
			// 		var show = true
			// 		var formDefaults = {}
			// 		switch (str) {
			// 			case '合格':
			// 				if (Number(that.baseFormData.OkAmount) < 0) {
			// 					that.showModal('报错', '合格数量不能小于0', '确认', '取消');
			// 					formDefaults = {
			// 						OkAmount: 0,
			// 						BadRate: 0,
			// 						BadAmount: that.baseFormData.CkAmount
			// 					};
			// 					that.resettableData()

			// 				} else {
			// 					if (Number(that.baseFormData.CkAmount) < Number(that.baseFormData.OkAmount)) {
			// 						that.showModal('报错', '合格数量不能大于检验数量', '确认', '取消');
			// 						formDefaults = {
			// 							OkAmount: Number(that.baseFormData.CkAmount),
			// 							BadRate: 0,
			// 							BadAmount: 0
			// 						};
			// 						that.resettableData()
			// 					} else {
			// 						formDefaults = {
			// 							BadAmount: Number(that.baseFormData.CkAmount) - Number(that.baseFormData
			// 								.OkAmount),
			// 							BadRate: ((Number(that.baseFormData.BadAmount) / Number(that
			// 								.baseFormData.CkAmount)) * 100).toFixed(2)
			// 						};
			// 					}
			// 				}

			// 				break;
			// 			case '不合格':
			// 				if (that.baseFormData.CkAmount == 0 || that.baseFormData.CkAmount == null) {
			// 					that.showModal('报错', '请先输入合格数量', '确认', '取消');
			// 					formDefaults = {
			// 						BadAmount: 0,
			// 						BadRate: 0
			// 					};
			// 					that.resettableData()
			// 				} else if (Number(that.baseFormData.BadAmount) < 0) {
			// 					that.showModal('报错', '不合格数量不能小于0', '确认', '取消');
			// 					formDefaults = {
			// 						BadAmount: 0,
			// 						BadRate: 0,
			// 						OkAmount: that.baseFormData.CkAmount
			// 					};
			// 					that.resettableData()
			// 				} else {
			// 					if (Number(that.baseFormData.CkAmount) < Number(that.baseFormData.BadAmount)) {
			// 						that.showModal('报错', '不合格数量不能大于检验数量', '确认', '取消');
			// 						formDefaults = {
			// 							OkAmount: Number(that.baseFormData.CkAmount),
			// 							BadRate: 0,
			// 							BadAmount: 0
			// 						};
			// 						that.resettableData()
			// 					} else {
			// 						formDefaults = {
			// 							OkAmount: Number(that.baseFormData.CkAmount) - Number(that.baseFormData
			// 								.BadAmount),
			// 							BadRate: ((Number(that.baseFormData.BadAmount) / Number(that
			// 								.baseFormData.CkAmount)) * 100).toFixed(2)
			// 						};
			// 					}
			// 				}
			// 				break;
			// 		}
			// 		that.UpdateAssignFormData(formDefaults)
			// 	},

			ApproveSClick(e) {
				var that = this
				console.log(e);
				var formDefaults = {
					ApproveName: e.name,
					Approve: e.id
				}
				that.UpdateAssignFormData(formDefaults)
				that.ApproveShow = false
			},
			ResultClick(e) {
				var that = this
				console.log(e);
				var formDefaults = {
					ResultName: e.name,
					Result: e.id
				}
				that.UpdateAssignFormData(formDefaults)
				that.Resultshow = false
			},
			changeResultshow() {
				var that = this
				if (!that.readOnlyShow) {
					that.Request.request('getJYResult', {
						FType: '首件检验'
					}, (ret) => {
						console.log(ret.data);
						if (ret.status == 200) {
							that.Resultlist = ret.data.ds
							that.Resultlist.map(item => {
								item.name = item.NAME
							})
							that.Resultshow = true
						}
					})
				}
			},

			list() {
				var that = this
				that.Request.request('scanJobOrderForJY', this.obj, (ret) => {
					const formDefaults = {
						...ret.data.ds[0],
						BadAmount: 0,
						Result: 1,
						ResultName: '合格',
						CkAmount: that.obj.FDailyQtt
					};
					that.assignFormData(that.baseFormData, formDefaults)

					var formData = {
						OkAmount: that.obj.FDailyQtt,
						BadRate: 100,
						BillDate: getFormatDateTime(new Date()),
						QCEmplName: that.$store.state.UserInfo.EmplName,
						QCEmplID: that.$store.state.UserInfo.EmplID,
						EquipmentID: that.$store.state.GuyueModule.MesBasicInfo.warehouse.EquipmentID
					}
					that.replaceFormData(that.baseFormData, that.baseFormData, formData)
					that.$forceUpdate()
				})
				this.obj.InspectionName = this.obj.FTypeName
				that.Request.request('scanJobOrderForJYDE', this.obj, (res) => {
					const formDefaults = {
						BadAmount: 0
					};
					that.assignFormData(that.baseFormData, formDefaults)
					res.data.ds1.map(item => {
						item.BadNum = 0
					})
					if (res.data.ds.length > 0) {
						that.CkAmountList = res.data.ds
					}
					if (res.data.ds1.length > 0) {
						that.tableData = res.data.ds1
					}

				})
			},
			exitButton() {
				var that = this
				switch (that.ApproveButton) {
					case '已审核':
						var obj = {
							FQty: that.baseFormData.ApproveName == '已审核' ? that.baseFormData.BadAmount : '返回',
							FSumQty: that.obj.FDailyQtt ? that.obj.FDailyQtt : 0,
							FDailyQtt: that.obj.FDailyQtt ? that.obj.FDailyQtt : 0,
							InspectionID: that.baseFormData.InspectionID ? that.baseFormData.InspectionID : 0
						}

						this.GoToLevel()
						uni.$emit('refselfValue', obj);
						break;
					default:
						that.showModal('通知', '确定退出吗？', '确认', '取消');
						return;
				}


			},
			changeLevel(list, data, row) {
				console.log(list);
				console.log(data);
				console.log(row);
				var that = this
				if (data.Name == row.Name) {
					that.initData = data
					that.initObj = row
					if (that.ApproveButton == "保存" || that.ApproveButton == "未审核") {
						that.showModal('通知', '当前页面未保存，是否先保存在关闭？', '是,保存并关闭', '否,直接关闭');
					} else if (that.HostApproveButton != '已审核' && that.ApproveButton == "已审核") {
						that.showModal('提示', '当前报工页面未保存!', '确认', '取消');

					} else if (that.HostApproveButton == '已审核' && that.ApproveButton == "已审核") {
						that.AndSetStateData()
					}
				} else {

					getchangeLevel(data)
					var obj = {
						FQty: that.baseFormData.ApproveName == '已审核' ? that.baseFormData.BadAmount : '返回',
						FSumQty: that.obj.FDailyQtt ? that.obj.FDailyQtt : 0,
						FDailyQtt: that.obj.FDailyQtt ? that.obj.FDailyQtt : 0,
						InspectionID: that.baseFormData.InspectionID ? that.baseFormData.InspectionID : 0
					}
					uni.$emit('refselfValue', obj);
					uni.$emit('refreshList');
				}
			},
			clearAfterCondition(data, condition) {
				// 遍历数组找到第一个满足条件的元素的索引  
				for (let i = 0; i < data.length; i++) {
					if (condition(data[i])) {
						console.log(i);
						// 如果找到，则截断数组  
						data.splice(i); // 注意：splice 会修改原数组  
						break;
					}
				}
			},
			AndSetStateData() {
				var that = this
				that.clearAfterCondition(that.initData, (item) => item
					.APPFunID == that
					.initObj.APPFunID);
				that.$store.commit('GuyueModule/ChangeAndSetStateData', {
					Name1: 'ModuleData_select',
					data: that.initData
				})
				var initData = JSON.parse(JSON.stringify(that.initData));
				parentData = initData[initData.length - 1]
				that.$refs.framework.ToLevel(parentData)
			},
		}
	}
</script>

<style lang="scss" >
	@import "../css/index.css";

	.table table {
		table-layout: fixed;

		tr td {
			input {
				width: 100%;
				background-color: #e7e7e7 !important;

			}

			view {
				width: 100%;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 10rpx;
			}
		}

	}

	.contentBox_top {
		padding: 0 10rpx 2rpx 10rpx;
		background-color: #fff;

		.u-button {
			background-color: #51d0d0;
			width: 5%;
			color: #fff;
		}
	}

	.bottomBtns2 {
		padding: 1%;
		width: 100%;
		display: flex;
		background-color: #fff;

		button {
			display: inline-block;
			color: #fff;
			background-color: #51d0d0;
			width: 20%;
			font-size: 16px;
		}

		.button0 {
			background-color: #ffce04;
		}

		.button3 {
			width: 30%;
		}
	}
</style>